var express = require('express');
var router = express.Router();
var BaseData = require('./config/db');
db = new BaseData();
db.connection.connect();

/* GET home page. */
router.get('/', function(req, res, next) {
	if(req.session.token) {
		res.redirect('/');
	} else {
		res.render('login', {
			title: 'Express'
		});
	}
});

router.get('/auth/', function(req, res, next) {
	if(req.session.token) {
		res.redirect('/');
	} else {
		res.redirect('/login');
	}

})

router.post('/auth/', function(req, res, next) {
	var uPattern = /^[a-zA-Z0-9_-]{4,16}$/;
	var WoUser = req.body.WoUser,
		WoPass = req.body.WoPass,
		agreement = req.body.agreement,
		submitBtn = req.body.submitBtn,
		msg = "";
	if(!uPattern.test(WoUser)) {
		msg = "用户名长度4-16位";
	}
	if(WoPass.length < 6) {
		msg = "密码最少6位"
	}
	if(agreement != "true") {
		msg = "未阅读用户协议和隐私条款"
	}
	if(msg) {
		res.json({
			"code": "3001",
			"msg": msg
		})
	} else {
		WoPass = db.Toolmd5(WoPass);
		db.connection.query('SELECT count(*),`User_id`,`CentStop`,`SubStop`,`LogStop` FROM `userinfo` where `User` = ? and `PassWord` = ?', [WoUser, WoPass], function(err, rows) {
			if(err) {
				res.json({
					"code": "3002",
					"msg": "系统出现错误,请联系管理员"
				})
			} else {
				if(rows[0]['count(*)'] > 0) {
					if(rows[0]['LogStop'] == 1) {
						res.json({
							"code": "3004",
							"msg": "账户违规，已停止使用"
						})
						return false;
					}
					req.session.token = null;
					db.connection.query('UPDATE `userinfo` SET `LogTime`= ?, `LogIp` = ? where `User` = ? and `PassWord` = ?', [new Date().toLocaleString(), getClientIp(req), WoUser, WoPass], function(err) {
						if(err) {
							res.json({
								"code": "3002",
								"msg": "登陆出现错误,请联系管理员"
							})
						} else {
							// 加密 User_id
							req.session.token = db.Toolaes(rows[0]['User_id'], "encryption") + "_" + redomToken();
							req.session.CentStop = rows[0]['CentStop']
							req.session.SubStop = rows[0]['SubStop']
							res.json();
						}
					})
				} else {
					res.json({
						"code": "3001",
						"msg": "账号或密码错误！"
					})
					return false;
				}

			}
		})
	}

	function getClientIp(req) {
		return req.headers['x-forwarded-for'] ||
			req.connection.remoteAddress ||
			req.socket.remoteAddress ||
			req.connection.socket.remoteAddress;
	};

	function redomToken() {
		var len = len || 32;
		var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
		var maxpos = chars.length;
		var str = '';

		for(var i = 0; i < len; i++) {
			str += chars.charAt(Math.floor(Math.random() * maxpos))
		}

		return str;
	}
})

router.get('/logout', function(req, res, next) {
	req.session.token = null;
	res.redirect('/');
})

module.exports = router;